<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitealbum
 * @copyright  Copyright 2010-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Core.php 2011-08-026 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitealbum_Api_Core extends Core_Api_Abstract {

  protected $_table;

  /**
   * Check lightbox is enable or not for photos show
   * @return bool
   */
  public function showLightBoxPhoto() {
    $session = new Zend_Session_Namespace('mobile');
    if (isset($session->mobile) && $session->mobile)
      return false;

    return SEA_SITEALBUM_LIGHTBOX;
  }

  /**
   * Get Photo lightbox Url
   * $photo : object
   * $params : array
   * @return url
   */
  public function getLightBoxPhotoHref($photo, $params = array()) {

    if (!$this->isLessThan417AlbumModule()) {
      $params = array_merge(array(
          'route' => 'sitealbum_extended',
          'reset' => true,
          'controller' => 'photo',
          'action' => 'light-box-view',
          'album_id' => $photo->album_id,
          'photo_id' => $photo->photo_id,
              ), $params);
    } else {
      $params = array_merge(array(
          'route' => 'sitealbum_extended',
          'reset' => true,
          'controller' => 'photo',
          'action' => 'light-box-view',
          'album_id' => $photo->collection_id,
          'photo_id' => $photo->photo_id,
              ), $params);
    }
    $route = $params['route'];
    $reset = $params['reset'];
    unset($params['route']);
    unset($params['reset']);
    return Zend_Controller_Front::getInstance()->getRouter()
                    ->assemble($params, $route, $reset);
  }

  public function getUserAlbums($user) {
    $table = Engine_Api::_()->getItemTable('album');
    $select = $table->select()->where("owner_type = ?", "user")->where("owner_id = ?", $user->user_id);
    if (!Engine_Api::_()->sitealbum()->canShowSpecialAlbum())
      $select->where('type IS NULL');
    return $table->fetchAll($select);
  }

  /**
   * get the tagged member in album
   * @params : $album_id
   * @return object
   */
  public function getTaggedUser($album_id) {

    $tableTagmaps = 'engine4_core_tagmaps';
    $userTable = Engine_Api::_()->getDbtable('users', 'user');
    $userTableName = $userTable->info('name');
    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentTableName = $parentTable->info('name');
    $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');

    $select = $parentTable->select()
            ->setIntegrityCheck(false)
            ->from($parentTableName, array());
    if (!$this->isLessThan417AlbumModule()) {
      $select->join($tableName, $tableName . '.album_id=' . $parentTableName . '.album_id', array());
    } else {
      $select->join($tableName, $tableName . '.collection_id=' . $parentTableName . '.album_id', array());
    }
    $select->join($tableTagmaps, $tableTagmaps . '.resource_id=' . $tableName . '.photo_id', array('count(tag_id) as number_of_tag'))
            ->join($userTableName, $tableTagmaps . '.tag_id=' . $userTableName . '.user_id', array($userTableName . '.user_id'))
            ->where($parentTableName . '.album_id = ?', $album_id)
            ->where($tableTagmaps . '.resource_type = ?', "album_photo")
            ->where($tableTagmaps . '.tag_type = ?', "user")
            ->group($tableTagmaps . ".tag_id")
            ->order('number_of_tag DESC');
    return $inSideAlbum = $table->fetchAll($select);
  }

  /**
   * get the tagged photos both you and owner
   */
  public function getTaggedYouAndOwnerPhotos($viewer_id, $owner_id, $limit=null) {

    $tableTagmaps = Engine_Api::_()->getDbtable('tagMaps', 'core');
    $tableTagmapsName = $tableTagmaps->info('name');

    $nestedSelect = $tableTagmaps->select()
            ->from($tableTagmapsName, array('resource_id'))
            ->where($tableTagmapsName . '.resource_type = ?', "album_photo")
            ->where($tableTagmapsName . '.tag_type = ?', "user")
            ->where($tableTagmapsName . '.tag_id = ?', $viewer_id);
    $viewerTagged = $tableTagmaps->fetchAll($nestedSelect);
    $resource_id = array();
    foreach ($viewerTagged as $value)
      $resource_id[] = $value->resource_id;
    // Not any tagged photo
    if (empty($resource_id))
      return;

    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentTableName = $parentTable->info('name');
    $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');
    $select = $tableTagmaps->select()
            ->from($tableTagmapsName, array('resource_id'))
            ->join($table->info('name'), $tableTagmapsName . '.resource_id=' . $tableName . '.photo_id', array());
    if (!$this->isLessThan417AlbumModule()) {
      $select->join($parentTableName, $parentTableName . '.album_id=' . $tableName . '.album_id', array());
    } else {
      $select->join($parentTableName, $parentTableName . '.album_id=' . $tableName . '.collection_id', array());
    }
    $select->where($tableTagmapsName . '.resource_type = ?', "album_photo")
            ->where($tableTagmapsName . '.resource_id in (?)', new Zend_Db_Expr("'" . join("', '", $resource_id) . "'"))
            ->where($tableTagmapsName . '.tag_id = ?', $owner_id)
            ->where('search = ?', true);

    if (!empty($limit)) {
      $select->limit($limit);
      $select->order('RAND()');
    }

    return Zend_Paginator::factory($select);
  }

  /**
   * get the tagged photos both you and owner
   */
  public function getTaggedInOthersPhotos($owner_id, $params=array()) {

    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentName = $parentTable->info('name');
    $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');
    $tableTagmaps = Engine_Api::_()->getDbtable('tagMaps', 'core');
    $tableTagmapsName = $tableTagmaps->info('name');

    $select = $tableTagmaps->select()
            ->from($tableTagmapsName, array('resource_id', 'creation_date'))
            ->join($tableName, $tableTagmapsName . '.resource_id=' . $tableName . '.photo_id', array());
    if (!$this->isLessThan417AlbumModule()) {
      $select->join($parentName, $parentName . '.album_id=' . $tableName . '.album_id', array());
    } else {
      $select->join($parentName, $parentName . '.album_id=' . $tableName . '.collection_id', array());
    }
    $select->where($tableTagmapsName . '.resource_type = ?', "album_photo")
            ->where($tableName . '.	owner_id <> ?', $owner_id)
            ->where($parentName . '.	owner_id <> ?', $owner_id)
            ->where($tableTagmapsName . '.tag_id = ?', $owner_id)
            ->where($tableTagmapsName . '.tag_type = ?', "user")
            ->where('search = ?', true)
            ->order($tableTagmapsName . '.creation_date DESC');

    return $tableTagmaps->fetchAll($select);
  }

  /**
   * get the tagged photos both you and owner
   */
  public function getCommentedPhotos($album_id, $params=array()) {
    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentTableName = $parentTable->info('name');
    $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');

    $select = $table->select()
            ->from($tableName);
    if (!$this->isLessThan417AlbumModule()) {
      $select->join($parentTableName, $parentTableName . '.album_id=' . $tableName . '.album_id', array())
              ->where($tableName . '.album_id = ?', $album_id);
    } else {
      $select->join($parentTableName, $parentTableName . '.album_id=' . $tableName . '.collection_id', array())
              ->where($tableName . '.collection_id = ?', $album_id);
    }

    $select
            ->where($tableName . '.comment_count > ?', 0)
            ->order($tableName . '.order')
            ->order($tableName . '.creation_date');

    return Zend_Paginator::factory($select);
  }

  /**
   * get the friends photo Albums
   */
  public function getFriendsPhotoAlbums($friend_ids, $albumLimit, $photoLimit) {

    $parentTable = Engine_Api::_()->getItemTable('album');
    $table = Engine_Api::_()->getItemTable('album_photo');

    $albumSelect = $parentTable->select()
            ->where('owner_id in (?)', new Zend_Db_Expr("'" . join("', '", $friend_ids) . "'"))
            ->where('search = ?', true)
            ->limit($albumLimit)
            ->order('Rand()');
    if (!Engine_Api::_()->sitealbum()->canShowSpecialAlbum())
      $albumSelect->where('type IS NULL');
    $albums = $parentTable->fetchAll($albumSelect);

    $collection = array();
    foreach ($albums as $value) {
      $photoSelect = $table->select()
              ->where('owner_id in (?)', new Zend_Db_Expr("'" . join("', '", $friend_ids) . "'"));
      if (!$this->isLessThan417AlbumModule()) {
        $photoSelect
                ->where('album_id = ?', $value->album_id);
      } else {
        $photoSelect
                ->where('collection_id = ?', $value->album_id);
      }
      $photoSelect->limit($photoLimit)
              ->order('Rand()');
      $photos = $parentTable->fetchAll($photoSelect);
      $count = count($photos);
      if ($count) {
        $collection[$value->album_id]['photo'] = $photos;
        $collection[$value->album_id]['album'] = $value;
      }
    }
    return $collection;
  }

  /**
   * get the friends photos
   */
  public function getFriendsPhotos($friend_ids, $photoLimit) {

    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentTableName = $parentTable->info('name');
    $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');
    $select = $table->select()
            ->from($tableName);
    if (!$this->isLessThan417AlbumModule()) {
      $select
              ->joinLeft($parentTableName, $parentTableName . '.album_id=' . $tableName . '.album_id', null);
    } else {
      $select
              ->joinLeft($parentTableName, $parentTableName . '.album_id=' . $tableName . '.collection_id', null);
    }
    $select
            ->where($parentTableName . '.search = ?', true)
            ->where($parentTableName . '.owner_id in (?)', new Zend_Db_Expr("'" . join("', '", $friend_ids) . "'"))
            ->limit($photoLimit)
            ->order('Rand()');
    if (!Engine_Api::_()->sitealbum()->canShowSpecialAlbum())
      $select->where($parentTableName . '.type IS NULL');
    return $table->fetchAll($select);
  }

  /**
   * get the featured photos
   */
  public function getFeaturedPhotos($params=array()) {
    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentTableName = $parentTable->info('name');
    $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');
    $select = $table->select()
            ->from($tableName);
    if (!$this->isLessThan417AlbumModule()) {
      $select
              ->joinLeft($parentTableName, $parentTableName . '.album_id=' . $tableName . '.album_id', null);
    } else {
      $select
              ->joinLeft($parentTableName, $parentTableName . '.album_id=' . $tableName . '.collection_id', null);
    }
    $select->where('search = ?', true)
            ->where($tableName . '.featured = ?', 1)
            ->order($tableName . '.creation_date DESC');

    if (isset($params['limit']) && !empty($params['limit'])) {
      if (!isset($params['start_index']))
        $params['start_index'] = 0;
      $select->limit($params['limit'], $params['start_index']);
    }
    return $table->fetchAll($select);
  }

  /**
   * get the previous photo
   */
  public function getPrevPhoto($current_photo, $params=array()) {
    if (!isset($params['type'])) {
      if (!$this->isLessThan417AlbumModule()) {
        return $current_photo->getPreviousPhoto();
      } else {
        return $current_photo->getPrevCollectible();
      }
    } else {
      return $this->getPhoto($current_photo, $params, -1);
    }
  }

  /**
   * get the next photo
   */
  public function getNextPhoto($current_photo, $params=array()) {
    if (!isset($params['type'])) {
      if (!$this->isLessThan417AlbumModule()) {
        return $current_photo->getNextPhoto();
      } else {
        return $current_photo->getNextCollectible();
      }
    } else {
      return $this->getPhoto($current_photo, $params, 1);
    }
  }

  /**
   * get the photo next/ previoues
   */
  public function getPhoto($collectible, $params=array(), $direction) {

    if (!isset($params['offset']) || empty($params['offset']))
      $index = $this->getCollectibleIndex($collectible, $params);
    else
      $index = $params['offset'];


    $index = $index + (int) $direction;

    $select = $this->getCollectibleSql($collectible, $params);

    // Check index bounds
    $count = $params['count'];
    if ($index >= $count) {
      $index -= $count;
    } else if ($index < 0) {
      $index += $count;
    }

    $select->limit(1, (int) $index);

    $rowset = $this->_table->fetchAll($select);
    if (null === $rowset) {
      // @todo throw?
      return null;
    }
    $row = $rowset->current();
    return Engine_Api::_()->getItem('album_photo', $row->photo_id);
  }

  /**
   * get the current photo index
   */
  public function getCollectibleIndex($collectible, $params=array()) {
    $select = $this->getCollectibleSql($collectible, $params);

    $i = 0;
    $index = 0;
    if (isset($params['count']) && !empty($params['count'])) {
      $select->limit($params['count']);
    }

    $rows = $this->_table->fetchAll($select);
    $totalCount = $rows->count();
    foreach ($rows as $row) {
      if ($row->getIdentity() == $collectible->getIdentity()) {
        $index = $i;
        break;
      }
      $i++;
    }
    return $index;
  }

  public function getCollectibleSql($collectible, $params=array()) {

    $parentTable = Engine_Api::_()->getItemTable('album');
    $parentName = $parentTable->info('name');
    $this->_table = $table = Engine_Api::_()->getItemTable('album_photo');
    $tableName = $table->info('name');
    $col = current($table->info("primary"));
    $select = $table->select()
            ->from($tableName, $col);
    if (!$this->isLessThan417AlbumModule()) {
      $select->join($parentName, $parentName . '.album_id=' . $tableName . '.album_id', null);
    } else {
      $select->join($parentName, $parentName . '.album_id=' . $tableName . '.collection_id', null);
    }
    $select
            ->where('search = ?', true);

    $type = $params['type'];
    switch ($type) {
      case 'featured':
        $select
                ->where($tableName . '.featured = ?', 1);

        break;
      case 'strip_modified':
        $type = 'modified_date';
        $select->order($tableName . '.modified_date DESC');
      case 'strip_creation':
        if (!Engine_Api::_()->sitealbum()->canShowSpecialAlbum())
          $select->where($parentName . '.type IS NULL');
        if (!isset($params['owner_id']) || empty($params['owner_id']))
          break;

        $select->where($tableName . '.owner_id = ?', $params['owner_id'])
                ->where($tableName . '.photo_hide = ?', 0);
        break;

      case 'tagged':

        if (!isset($params['owner_id']) || empty($params['owner_id']))
          break;
        $owner_id = $params['owner_id'];

        $this->_table = $tableTagmaps = Engine_Api::_()->getDbtable('tagMaps', 'core');
        $tableTagmapsName = $tableTagmaps->info('name');

        $select = $tableTagmaps->select()
                ->setIntegrityCheck(false)
                ->from($tableTagmapsName, array('resource_id', 'creation_date'))
                ->join($tableName, $tableTagmapsName . '.resource_id=' . $tableName . '.photo_id', array('photo_id'));

        if (!$this->isLessThan417AlbumModule()) {
          $select->join($parentName, $parentName . '.album_id=' . $tableName . '.album_id', array());
        } else {
          $select->join($parentName, $parentName . '.album_id=' . $tableName . '.collection_id', array());
        }
        $select->where($tableTagmapsName . '.resource_type = ?', "album_photo")
                ->where($tableName . '.	owner_id <> ?', $owner_id)
                ->where($parentName . '.	owner_id <> ?', $owner_id)
                ->where($tableTagmapsName . '.tag_id = ?', $owner_id)
                ->where($tableTagmapsName . '.tag_type = ?', "user")
                ->where('search = ?', true)
                ->order($tableTagmapsName . '.creation_date DESC');
        return $select;
        break;
      default :
        $select->order($tableName . ".$type DESC");
        if (!Engine_Api::_()->sitealbum()->canShowSpecialAlbum())
          $select->where($parentName . '.type IS NULL');
        break;
    }
    if ($type != "modified_date" && $type != "creation_date")
      $select->order($tableName . '.photo_id DESC');
    return $select;
  }

  public function canSendUserMessage($subject) {
    // Not logged in
    $viewer = Engine_Api::_()->user()->getViewer();
    if (!$viewer->getIdentity() || $viewer->getGuid(false) === $subject->getGuid(false)) {
      return false;
    }
    // Get setting?
    $permission = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'messages', 'create');
    if (Authorization_Api_Core::LEVEL_DISALLOW === $permission) {
      return false;
    }
    $messageAuth = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'messages', 'auth');
    if ($messageAuth == 'none') {
      return false;
    } else if ($messageAuth == 'friends') {
      // Get data
      $direction = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('user.friends.direction', 1);
      if (!$direction) {
        //one way
        $friendship_status = $viewer->membership()->getRow($subject);
      }
      else
        $friendship_status = $subject->membership()->getRow($viewer);

      if (!$friendship_status || $friendship_status->active == 0) {
        return false;
      }
    }
    return true;
  }

  public function isLessThan417AlbumModule() {
    $albumModule = Engine_Api::_()->getDbtable('modules', 'core')->getModule('album');
    $albumModuleVersion = $albumModule->version;
    if ($albumModuleVersion < '4.1.7') {
      return true;
    } else {
      return false;
    }
  }

  public function deleteSuggestion($entity, $entity_id, $notifications_type) {
    $viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
    $is_moduleEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('suggestion');
    if (!empty($is_moduleEnabled)) {
      $suggestion_table = Engine_Api::_()->getItemTable('suggestion');
      $suggestion_table_name = $suggestion_table->info('name');
      $suggestion_select = $suggestion_table->select()
              ->from($suggestion_table_name, array('suggestion_id'))
              ->where('owner_id = ?', $viewer_id)
              ->where('entity = ?', $entity)
              ->where('entity_id = ?', $entity_id);
      $suggestion_array = $suggestion_select->query()->fetchAll();
      if (!empty($suggestion_array)) {
        foreach ($suggestion_array as $sugg_id) {
          Engine_Api::_()->getItem('suggestion', $sugg_id['suggestion_id'])->delete();
          Engine_Api::_()->getDbtable('notifications', 'activity')->delete(array('object_id = ?' => $sugg_id['suggestion_id'], 'type = ?' => $notifications_type));
        }
      }
    }
    return;
  }

  public function isModulesSupport() {
    $modArray = array(
        'facebookse' => '4.1.7',
        'suggestion' => '4.1.7p1'
    );
    $finalModules = array();
    foreach ($modArray as $key => $value) {
      $isModEnabled = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled($key);
      if (!empty($isModEnabled)) {
        $getModVersion = Engine_Api::_()->getDbtable('modules', 'core')->getModule($key);
        $isModSupport = strcasecmp($getModVersion->version, $value);
        if ($isModSupport < 0) {
          $finalModules[] = $getModVersion->title;
        }
      }
    }
    return $finalModules;
  }

  /**
   * Check make profile photo is enable or not
   * @return bool
   */
//  public function canMakeProfilePhoto() {
//    return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitealbum.photo.makeprofile', 1);
//  }

  /**
   * Check download photo is enable or not
   * @return bool
   */
//  public function canDownloadPhoto() {
//    return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitealbum.photo.download', 1);
//  }

  /**
   * Check download photo is enable or not
   * @return bool
   */
  public function canShowSpecialAlbum() {
    return (bool) Engine_Api::_()->getApi('settings', 'core')->getSetting('sitealbum.photo.specialalbum', 1);
  }

  /**
   * Set Orders of Photos
   * @return bool
   */
  public function setPhotosOrder($album_id) {

    $photoTable = Engine_Api::_()->getItemTable('album_photo');
    $album_id_Col = "album_id";
    if ($this->isLessThan417AlbumModule()) {
      $album_id_Col = "collection_id";
    }
    $conutOrder = $photoTable->select()
            ->from($photoTable, 'photo_id')
            ->where("$album_id_Col = ?", $album_id)
            ->where('`order` = ?', 0)
            ->order('order ASC')
            ->limit(2)
            ->query()
            ->fetchAll(Zend_Db::FETCH_COLUMN);
    $count = count($conutOrder);
    if ($count <= 1)
      return;

    $currentOrder = $photoTable->select()
            ->from($photoTable, 'photo_id')
            ->where("$album_id_Col = ?", $album_id)
            ->order('order ASC')
            ->query()
            ->fetchAll(Zend_Db::FETCH_COLUMN);
    for ($i = 0, $l = count($currentOrder); $i < $l; $i++) {
      $photo_id = $currentOrder[$i];
      $photoTable->update(array(
          'order' => $i,
              ), array(
          'photo_id = ?' => $photo_id,
      ));
    }
  }

}
?>
